package xyz.huanggy.minio.upload.minio;


import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Fu Kai
 * @since 20220408
 */

@Configuration
public class MinioConfig {

    @Autowired
    private MinioProperties minioProperties;

    public MinioClient minioClient() {

        MinioClient.Builder minioClientBuilder = MinioClient.builder();
        return minioClientBuilder.endpoint( minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getAccessSecret())
                .build();
    }

    @Bean
    public CustomMinioClient customizedMinioClient() {
        CustomMinioClient customMinioClient = new CustomMinioClient(minioClient());
        createBucket(customMinioClient);
        return customMinioClient;
    }


    public void createBucket(MinioClient client) {
        try {
            String bucketName = minioProperties.getBucket();

            // 检查桶是否存在
            boolean isExist = client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                // 如果桶不存在，则创建一个新桶
                client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                System.out.println("桶 " + bucketName + " 已成功创建！");
            } else {
                System.out.println("桶 " + bucketName + " 已存在！");
            }
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
    }


}
